/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.common.message;

import java.io.Serializable;

import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author tangli
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-5-7 上午9:39:09          tangli_ITSM        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class AsyncSession {
    private static final Logger logger = LoggerFactory.getLogger(AsyncSession.class);
    private static final long TIME_OUT = 5 * 60 * 1000L;
    private String queueName = null;
    private Session session;
    private Destination destination;
    private int ackMode = Session.AUTO_ACKNOWLEDGE;
    private MessageProducer producer;

    public AsyncSession(String queueName) {
        this.queueName = queueName;
        init();
    }

    private void init() {
        try {
            session = BsmActiveMQFactory.getInstance().getSession(false, ackMode);
            destination = session.createQueue(queueName);
            producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            producer.setTimeToLive(1000 * 60 * 60 * 6);
        } catch (Exception ex) {
            logger.error("error create message queue:" + this.queueName, ex);
        }
    }

    public void send(Serializable msg) throws JMSException {
        ObjectMessage objectMessage = session.createObjectMessage(msg);
        producer.send(objectMessage);
    }

    public void close() {
        if (session != null) {
            try {
                session.close();
            } catch (Exception e) {
            }
        }
    }
}
